<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="批次编号" prop="batchNo">
        <el-input
          v-model="queryParams.batchNo"
          placeholder="请输入批次编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品" prop="batchProduct">
        <el-input
          v-model="queryProductName"
          placeholder="请选择产品"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        >
          <el-button slot="append" icon="el-icon-search" @click="selectProduct(0)" :disabled="false"></el-button>
        </el-input>
      </el-form-item>
      <el-form-item label="种植日期" prop="batchPlantTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.batchPlantTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择种植日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="收获日期" prop="batchHarvestTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.batchHarvestTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择收获日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="负责人" prop="batchPerson">
        <el-input
          v-model="queryParams.batchPerson"
          placeholder="请输入负责人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="负责人联系方式" prop="batchPersonPhone">
        <el-input
          v-model="queryParams.batchPersonPhone"
          placeholder="请输入负责人联系方式"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['beyond:batch:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['beyond:batch:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['beyond:batch:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
		  :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['beyond:batch:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="batchList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="" align="center" prop="batchId" /> -->
      <el-table-column label="批次编号" align="center" prop="batchNo" />
      <el-table-column label="产品" align="center" prop="productName" />
      <el-table-column label="种植日期" align="center" prop="batchPlantTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.batchPlantTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收获日期" align="center" prop="batchHarvestTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.batchHarvestTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="负责人" align="center" prop="batchPerson" />
      <el-table-column label="负责人联系方式" align="center" prop="batchPersonPhone" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-printer"
            @click="print(scope.row)"
          >打印</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['beyond:batch:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['beyond:batch:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改批次信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="批次编号" prop="batchNo">
          <el-input v-model="form.batchNo" placeholder="输入以后就按照输入的，不输入系统会自动生成" />
        </el-form-item>
        <el-form-item label="产品" prop="batchProduct">
          <el-input v-model="productName" placeholder="请输入产品" >
            <el-button slot="append" icon="el-icon-search" @click="selectProduct(1)" :disabled="false"></el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="种植日期" prop="batchPlantTime">
          <el-date-picker clearable size="small"
            v-model="form.batchPlantTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择种植日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="收获日期" prop="batchHarvestTime">
          <el-date-picker clearable size="small"
            v-model="form.batchHarvestTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择收获日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="负责人" prop="batchPerson">
          <el-input v-model="form.batchPerson" placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item label="负责人联系方式" prop="batchPersonPhone">
          <el-input v-model="form.batchPersonPhone" placeholder="请输入负责人联系方式" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="产品选择" :visible.sync="productOpen" width="900px">
      <div>
        <ProductSelect @productSelect="productSelect"/>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="productSelectSubmitForm">确 定</el-button>
        <el-button @click="productSelectCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import { listBatch, getBatch, delBatch, addBatch, updateBatch, exportBatch, batchQRCode } from "@/api/trace/batch";
import ProductSelect from '@/components/ProductSelect'
import iFrame from '@/components/iFrame'
import printJS from 'print-js';

export default {
  components: {
    ProductSelect,
    iFrame
  },
  name: "Batch",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 查询产品名称
      queryProductName: '',
      // 产品名称
      productName: '',
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 选择产品值
      selectProductValue: null,
      // 总条数
      total: 0,
      // 批次信息表格数据
      batchList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //是否显示产品选择对话框
      productOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        batchNo: null,
        batchProduct: null,
        batchPlantTime: null,
        batchHarvestTime: null,
        batchPerson: null,
        batchPersonPhone: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      //判断选择产品用于查询还是新增
      selectProductType: false,

    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询批次信息列表 */
    getList() {
      this.loading = true;
      listBatch(this.queryParams).then(response => {
        this.batchList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        batchId: null,
        batchNo: null,
        batchProduct: null,
        batchPlantTime: null,
        batchHarvestTime: null,
        batchPerson: null,
        batchPersonPhone: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
      this.queryProductName = '';
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
      this.queryProductName = '';
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.batchId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.productName = ''
      this.title = "添加批次信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const batchId = row.batchId || this.ids
      getBatch(batchId).then(response => {
        this.form = response.data;
        this.productName = response.data.productName
        this.open = true;
        this.title = "修改批次信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.batchId != null) {
            updateBatch(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBatch(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const batchIds = row.batchId || this.ids;
      this.$confirm('是否确认删除批次信息编号为"' + batchIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delBatch(batchIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有批次信息数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportBatch(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    },
    //选择商品
    selectProduct(type){
      if(type == 0){
        this.selectProductType = true;
        this.queryProductName = ''
        this.productOpen = true;
      }else{
        this.selectProductType = false;
        this.productName = ''
        this.productOpen = true;
      }
    },
    // 产品选择点击取消
    productSelectCancel(){
      this.productOpen = false;
    },
    //选中产品传递
    productSelect(data){
      this.selectProductValue = data;
    },
    //产品选择点击确定
    productSelectSubmitForm(){
      if(this.selectProductType){
        this.queryParams.batchProduct = this.selectProductValue.productId
        this.queryProductName = this.selectProductValue.productName
        this.productOpen = false;
      }else{
        this.form.batchProduct = this.selectProductValue.productId
        this.productName = this.selectProductValue.productName
        this.productOpen = false;
      }
      
    },

    //打印
    print(row){
      batchQRCode({batchNo:row.batchNo}).then(response =>{
        var juicer = require('juicer');
        var tpl = ''
        const xhr = new XMLHttpRequest()
        const okStatus = document.location.protocol === 'file:' ? 0 : 200
        // xhr.open('GET','/xw-trace/PrintTemplate/print.html',false)
        // xhr.open('GET','/ztrace/PrintTemplate/print.html',false)
        xhr.open('GET','/PrintTemplate/print.html',false)
        xhr.overrideMimeType('text/html;charset=utf-8')
        xhr.send(null)
        if(xhr.status === okStatus) {
          tpl = xhr.responseText
        }
        var html = juicer(tpl,response.data)
        printJS({
          printable: [html],
          type: 'raw-html',
          style: '@page {margin:0}',
          targetStyles: ["*"]
        })

      });      
    }
  }
};
</script>
